import { useState, useEffect, useRef } from "react";
import { useParams, useNavigate } from "react-router-dom";
import * as echarts from "echarts";
import { ArrowLeft, Calendar, TrendingUp, AlertCircle } from "lucide-react";
import stockApi, { StockHistory, StockInfo } from "../services/stockApi";

type TimePeriod = "daily" | "30m" | "60m" | "3month" | "6month" | "1year" | "2year";

interface TimePeriodOption {
  value: TimePeriod;
  label: string;
  description: string;
  days?: number; // 添加天数字段用于计算数据范围
}

const timePeriods: TimePeriodOption[] = [
  { value: "daily", label: "日线", description: "每日K线", days: 90 },
  { value: "30m", label: "30分线", description: "30分钟K线", days: 7 },
  { value: "60m", label: "60分线", description: "60分钟K线", days: 14 },
  { value: "3month", label: "3个月", description: "3个月历史", days: 90 },
  { value: "6month", label: "6个月", description: "6个月历史", days: 180 },
  { value: "1year", label: "1年", description: "1年历史", days: 365 },
  { value: "2year", label: "2年", description: "2年历史", days: 730 },
];

// 获取股票名称的映射
const getStockName = (symbol: string): string => {
  const stockNames: { [key: string]: string } = {
    "000001": "平安银行",
    "000002": "万科A",
    "000858": "五粮液",
    "600000": "浦发银行",
    "600036": "招商银行",
    "600519": "贵州茅台",
    "600887": "伊利股份"
  };
  return stockNames[symbol] || `股票${symbol}`;
};

// 转换API数据为ECharts格式
const convertToEChartsData = (stockHistory: StockHistory) => {
  return stockHistory.data.map(item => ([
    item.date,
    item.open,
    item.close,
    item.low,
    item.high,
    item.volume
  ]));
};

export default function Chart() {
  const { stockCode } = useParams<{ stockCode: string }>();
  const navigate = useNavigate();
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [selectedPeriod, setSelectedPeriod] = useState<TimePeriod>("daily");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [stockInfo, setStockInfo] = useState<StockInfo | null>(null);
  const [apiHealthy, setApiHealthy] = useState<boolean | null>(null);

  // 初始化图表
  useEffect(() => {
    if (chartRef.current) {
      chartInstance.current = echarts.init(chartRef.current);
      
      // 监听窗口大小变化
      const handleResize = () => {
        chartInstance.current?.resize();
      };
      window.addEventListener('resize', handleResize);
      
      return () => {
        window.removeEventListener('resize', handleResize);
        chartInstance.current?.dispose();
      };
    }
  }, []);

  // 检查API健康状态
  useEffect(() => {
    const checkApiHealth = async () => {
      try {
        const healthy = await stockApi.checkApiHealth();
        setApiHealthy(healthy);
      } catch (error) {
        setApiHealthy(false);
      }
    };
    
    checkApiHealth();
  }, []);

  // 获取股票基本信息
  useEffect(() => {
    const fetchStockInfo = async () => {
      if (!stockCode || !apiHealthy) return;
      
      try {
        const info = await stockApi.getStockInfo(stockCode);
        setStockInfo(info);
      } catch (error) {
        console.error('Failed to fetch stock info:', error);
        // 股票信息获取失败不影响图表显示
      }
    };
    
    fetchStockInfo();
  }, [stockCode, apiHealthy]);

  // 更新图表数据
  useEffect(() => {
    const fetchChartData = async () => {
      if (!chartInstance.current || !stockCode) return;
      
      setLoading(true);
      setError(null);
      
      try {
        // 检查API是否可用
        if (apiHealthy === false) {
          throw new Error('股票数据API服务不可用，请确保后端服务已启动');
        }
        
        // 如果API健康但还未完成检查，等待一下
        if (apiHealthy === null) {
          throw new Error('正在连接股票数据服务...');
        }
        
        // 根据选择的时间周期计算日期范围
        const selectedPeriodOption = timePeriods.find(p => p.value === selectedPeriod);
        const days = selectedPeriodOption?.days || 365;
        
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - days);
        
        const formatDate = (date: Date) => {
          return date.toISOString().split('T')[0].replace(/-/g, '');
        };
        
        // 获取股票历史数据，传入计算好的日期范围
        const actualPeriod = ['3month', '6month', '1year', '2year'].includes(selectedPeriod) ? 'daily' : selectedPeriod;
        const stockHistory = await stockApi.getStockHistory(
          stockCode, 
          actualPeriod,
          formatDate(startDate),
          formatDate(endDate)
        );
        const klineData = convertToEChartsData(stockHistory);
        
        if (klineData.length === 0) {
          throw new Error('暂无数据');
        }
        
        const stockName = stockInfo?.name || getStockName(stockCode);
        const periodLabel = timePeriods.find(p => p.value === selectedPeriod)?.label || selectedPeriod;
        
        const option = {
          title: {
            text: `${stockName}(${stockCode}) - ${periodLabel}`,
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            formatter: function(params: any) {
              const data = params[0].data;
              const originalData = klineData[params[0].dataIndex];
              return `
                日期: ${originalData[0]}<br/>
                开盘: ${originalData[1]}<br/>
                收盘: ${originalData[2]}<br/>
                最低: ${originalData[3]}<br/>
                最高: ${originalData[4]}
              `;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '8%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: klineData.map(item => item[0]),
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            min: 'dataMin',
            max: 'dataMax',
            axisLabel: {
              show: false
            }
          },
          yAxis: {
            scale: true,
            splitArea: {
              show: true
            }
          },
          dataZoom: [
            {
              type: 'inside',
              start: Math.max(0, ((klineData.length - 40) / klineData.length) * 100), // 默认显示最近40个交易日
              end: 100,
              zoomOnMouseWheel: true,
              moveOnMouseMove: true,
              minSpan: 5, // 最小显示5%的数据
              maxSpan: 100 // 最大显示100%的数据
            },
            {
              show: true, // 显示滑动条，方便用户快速定位
              type: 'slider',
              bottom: 10,
              start: Math.max(0, ((klineData.length - 40) / klineData.length) * 100), // 默认显示最近40个交易日
              end: 100,
              height: 20,
              handleSize: 10,
              textStyle: {
                fontSize: 10
              },
              dataBackground: {
                lineStyle: {
                  color: '#ddd'
                },
                areaStyle: {
                  color: '#f5f5f5'
                }
              },
              minSpan: 5, // 最小显示5%的数据
              maxSpan: 100, // 最大显示100%的数据
              zoomLock: false // 允许缩放
            }
          ],
          series: [
            {
              name: 'K线图',
              type: 'candlestick',
              data: klineData.map(item => [item[1], item[2], item[3], item[4]]),
              itemStyle: {
                color: '#dc2626',
                color0: '#16a34a',
                borderColor: '#dc2626',
                borderColor0: '#16a34a'
              }
            }
          ]
        };
        
        chartInstance.current?.setOption(option);
      } catch (error) {
        console.error('Failed to fetch chart data:', error);
        setError(error instanceof Error ? error.message : '获取数据失败');
      } finally {
        setLoading(false);
      }
    };
    
    fetchChartData();
  }, [stockCode, selectedPeriod, apiHealthy, stockInfo]);

  const handlePeriodChange = (period: TimePeriod) => {
    setSelectedPeriod(period);
  };

  const handleAnalysis = () => {
    navigate(`/analysis/${stockCode}`);
  };

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-7xl mx-auto">
        {/* 头部导航 */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <button
                onClick={() => navigate('/')}
                className="flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors"
              >
                <ArrowLeft size={20} />
                返回首页
              </button>
              <div className="h-6 w-px bg-gray-300"></div>
              <h1 className="text-xl font-semibold text-gray-800">
                股票代码: {stockCode}
              </h1>
              {stockInfo && (
                <div className="text-sm text-gray-600">
                  {stockInfo.name} ({stockInfo.symbol})
                </div>
              )}
            </div>
            <div className="flex items-center gap-4">
              {apiHealthy === false && (
                <div className="flex items-center gap-2 text-red-600">
                  <AlertCircle size={16} />
                  <span className="text-sm">API服务不可用</span>
                </div>
              )}
              <button
                onClick={handleAnalysis}
                className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors"
              >
                <TrendingUp size={20} />
                历史对比分析
              </button>
            </div>
          </div>
        </div>

        {/* 时间周期选择 */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <div className="flex items-center gap-2 mb-3">
            <Calendar size={20} className="text-gray-600" />
            <span className="font-medium text-gray-800">时间周期</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {timePeriods.map((period) => (
              <button
                key={period.value}
                onClick={() => handlePeriodChange(period.value)}
                disabled={loading || apiHealthy === false}
                className={`px-4 py-2 rounded-lg border transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                  selectedPeriod === period.value
                    ? 'bg-blue-600 text-white border-blue-600'
                    : 'bg-white text-gray-700 border-gray-300 hover:border-blue-300 hover:bg-blue-50'
                }`}
              >
                <div className="text-sm font-medium">{period.label}</div>
                <div className="text-xs opacity-75">{period.description}</div>
              </button>
            ))}
          </div>
        </div>

        {/* K线图表 */}
        <div className="bg-white rounded-lg shadow-sm p-4">
          <div className="relative">
            {loading && (
              <div className="absolute inset-0 bg-white bg-opacity-75 flex items-center justify-center z-10">
                <div className="flex items-center gap-2 text-gray-600">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                  <span>加载中...</span>
                </div>
              </div>
            )}
            {error && (
              <div className="absolute inset-0 bg-white bg-opacity-90 flex items-center justify-center z-10">
                <div className="text-center">
                  <AlertCircle size={48} className="text-red-500 mx-auto mb-4" />
                  <p className="text-red-600 mb-4">{error}</p>
                  <button
                    onClick={() => window.location.reload()}
                    className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
                  >重新加载</button>
                </div>
              </div>
            )}
            <div
              ref={chartRef}
              className="w-full h-96"
              style={{ minHeight: '400px' }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}